#include <iostream>
#include <unordered_map>
#include <queue>

using namespace std;
string s;
string aim = "123804765";
unordered_map<string, int> dist;
queue<string> q;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
void bfs()
{
    q.push(s);
    dist[s] = 0;
    while(q.size())
    {
        auto t = q.front(); q.pop();
        int pos = 0;
        //先找到0所在的位置的下标
        while(t[pos] != '0') pos++;  //这里已经找到了
        int x = pos / 3 , y = pos % 3;
        for(int k = 0;k < 4;k ++)
        {
            int a = x + dx[k] , b = dy[k] + y;
            if(a >= 0 && b >= 0 && a <= 2 && b <= 2)
            {
                string next = t; //不能修改t的值 用一个临时变量存
                //(x , y) 与 (a , b) 交换
                int p = 3 * a + b;
                swap(next[pos] , next[p]);
                //看一下有没有存在
                if(dist.count(next)) continue;

                dist[next] = dist[t] + 1;
                q.push(next);
                if(next == aim) return;
            }
        }
    }
}
int main()
{
    cin >> s;
    bfs();
    cout << dist[aim] << endl;
    return 0;
}